#include "tcpServer.hpp"
#include "daemon.hpp"

#include <memory>
using namespace std;
using namespace Server;
enum
{
    OK = 0,
    DIV_ZERO,
    MOD_ZERO,
    OP_ERROR
};
static void Usage(const string &arg)
{
    cout << "\nplease input ./tcpServer local_port\n"
         << endl;
}

// 网络计算器业务逻辑
void handlerEnter(const Request &req, Response &resp)
{
    int x = req.x;
    int y = req.y;
    char op = req.op;

    int exitcode = 0;
    int result = 0;

    switch (op)
    {
    case '+':
        result = x + y;
        break;
    case '-':
        result = x - y;
        break;
    case '*':
        result = x * y;
        break;
    case '/':
    {
        if (0 == y)
            exitcode = DIV_ZERO;
        else
        {
            result = x / y;
        }
    }
    break;
    case '%':
    {
        if (0 == y)
            exitcode = MOD_ZERO;
        else
        {
            result = x % y;
        }
    }
    break;
    default:
        exitcode = OP_ERROR;
        break;
    }

    resp.exitcode = exitcode;
    resp.result = result;
}


int main(int argc, char *argv[])
{
    cout << getpid() << endl;
    cout << pthread_self() << endl;
    if (argc != 2)
    {
        Usage(argv[0]);
        logMessage(FATAL, "Usage error");
        exit(USAGE_ERR);
    }
    logMessage(NORMAL, "Usage success");
    unique_ptr<TcpServer> ptsv(new TcpServer(atoi(argv[1]), handlerEnter));


    ptsv->initServer();
    //daemonSelf();
    ptsv->start();
    return 0;
}
